#include <iostream>
#include<stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <cerrno>
#include <unistd.h>

using namespace std;

void setnoblock(int fd)
{
    // F_GETFL：获取文件描述符的状态标记
    int f = fcntl(fd, F_GETFL);
    if (f < 0)
    {
        cerr << "fcnt err" << endl;
        return;
    }
    // 获取成功后，就可以把把文件描述符设置为非阻塞
    fcntl(fd, F_SETFL, f | O_NONBLOCK);
    cout << "set noblock success" << endl;
}

int main()
{
    char buffer[1024];
    setnoblock(0);  
    sleep(1);
    while (true)
    {
        // printf("Please Enter# ");
        // fflush(stdout);

        int n = read(0, buffer, sizeof(buffer) - 1);
        // 读取成功
        if (n > 0)
        {
            buffer[n - 1] = 0;
            cout << "echo: " << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "read done" << endl;
            break;
        }
        else
        {
            if (errno == EWOULDBLOCK)
            {
                cout << "0 fd source not ready" << endl;
                sleep(1);
            }
            else
            {
                cout << "read err, n = " << n << " errno code: " << errno << " errstring: " << strerror(errno) << endl;
                sleep(1);
                // break;
            }
        }
    }

    return 0;
}